package com.store.orm.mysql.crud.impl;


import com.store.orm.mysql.MySQLUtil;
import com.store.orm.mysql.crud.Update;
import com.store.orm.mysql.crud.filter.Filtration;
import com.store.orm.util.MapUtil;
import com.store.orm.util.StringUtil;

import java.util.*;

import static com.store.orm.common.KeyWord.*;


/**
 * 修改数据时，传入的对象不能所有字段都为空
 *
 * @author 宫静雨
 * @version 1.0
 */
public class MySQLUpdate implements Update {
    private MySQLUtil UTIL;

    public MySQLUpdate(MySQLUtil UTIL) {
        this.UTIL = UTIL;
    }

    public MySQLUtil getUTIL() {
        return UTIL;
    }

    private Map<String, List<Object>> toResult(String tableName, Map<String, Object> map, Filtration filtration) {
        StringBuilder sb = new StringBuilder();
        if (map.keySet().size() == 0) {
            throw new RuntimeException("传入的对象所有值均为空");
        }
        sb.append(UPDATE).append(tableName).append(BLANK).append(SET);
        map.keySet().forEach(k -> sb.append(k).append(EQUAL_TO).append(QUESTION).append(COMMA).append(BLANK));
        sb.delete(sb.lastIndexOf(COMMA), sb.length());
        String str = filtration.get();
        if (!StringUtil.isBlank(str)) {
            sb.append(str);
        } else if (!UTIL.isUpdateAll()) {
            throw new RuntimeException("禁止修改时不带条件参数");
        }
        List<Object> list = new ArrayList<>(map.values());
        return new MapUtil<String, List<Object>>().put(sb.toString(), list).linked();
    }

    @Override
    public <T> Map<String, List<Object>> update(Filtration filter, T t) {
        Class<?> cls = t.getClass();
        String tableName = UTIL.getTableName(cls);
        Map<String, Object> map = UTIL.parseTToMap(t);
        return toResult(tableName, map, filter);
    }

    /**
     * 支持日期类型的字符串
     *
     * @param filter
     * @param cls
     * @param json
     * @return
     */
    @Override
    public Map<String, List<Object>> update(Filtration filter, Class<?> cls, String json) {
        String tableName = UTIL.getTableName(cls);
        if (Objects.isNull(json) || StringUtil.isBlank(json)) {
            throw new RuntimeException("提供的 JSON 为空字符串");
        }
        Map<String, Object> map = UTIL.parseJsonToMap(json);
        return toResult(tableName, map, filter);
    }

    @Override
    public Map<String, List<Object>> update(Filtration filter, Class<?> cls, LinkedHashMap<String, Object> map) {
        String tableName = UTIL.getTableName(cls);
        return toResult(tableName, map, filter);
    }

    @Override
    public Map<String, List<Object>> update(String sql, Object... args) {
        List<Object> list = Arrays.asList(args);
        return new MapUtil<String, List<Object>>().put(sql, list).linked();
    }
}